# -*- coding:utf-8 -*-
# @File    : readRelevance.py
# ****************************
import logging
import re,jsonpath
from ast import literal_eval

# __relevance = ""
__relevance = []


def get_value(data, value):
    """获取数据中的值

    :param data:
    :param value:
    :return:
    """

    # global __relevance
    if isinstance(data, dict):
        # if value in data:
        #     __relevance = data[value]
        # else:
        #     for key in data:
        #         __relevance = get_value(data[key], value)
        for key in data:
            if isinstance(data[key], dict):
                get_value(data[key], value)
            elif isinstance(data[key], list):
                for each in data[key]:
                    if isinstance(each, dict):
                        get_value(each, value)
                # for each in data[key]:
                #     if isinstance(each, dict):
                #         break
                else:
                    if key == value:
                        __relevance.append(data[key])
            else:
                if key == value:
                    __relevance.append(data[key])
    elif isinstance(data, list):
        for key in data:
            if isinstance(key, dict):
                # __relevance = get_value(key, value)
                # break
                get_value(key, value)
    return __relevance


def get_relevance(data, relevance_list, relevance=None):
    """获取关联键值对

    :param data:
    :param relevance_list:
    :param relevance:
    :return:
    """
    global __relevance
    # 获取关联键列表
    relevance_list = re.findall(r"\${(.*?)}", str(relevance_list))
    # 去除参数[n]标识
    for index, value in enumerate(relevance_list):
        mark = re.findall(r"\[\-?[0-9]*\]", value)
        # if mark:
        #     relevance_list[index] = value.strip(mark[0])
        for m in mark:
            value = value.replace(m, '')
        relevance_list[index] = value
    # 去除重复参数
    relevance_list = list(set(relevance_list))
    logging.debug("获取关联键列表:\n%s" % relevance_list)

    # 判断关联键和源数据是否有值
    if (not data) or (not relevance_list):
        return relevance

    # 判断是否存在其他关联键对象
    if not relevance:
        relevance = dict()

    # 遍历关联键
    for each in relevance_list:
        # 只考虑一个关联键一个值
        # if each in relevance:
        #     pass
        # else:
        #     # 从结果中提取关联键的值
        #     relevance[each] = get_value(data, each)

        # 考虑到一个关联键多个值
        relevance_value = get_value(data, each)
        if relevance_value:
            if each in relevance:
                tmp = relevance[each]
                if isinstance(tmp, list):
                    tmp += relevance_value
                    relevance[each] = tmp
                else:
                    tmp2 = relevance_value.insert(0, tmp)
                    relevance[each] = tmp2
            else:
                relevance[each] = relevance_value
        __relevance = []
    logging.debug("提取关联键对象:\n%s" % relevance)
    return relevance


def get_address_relevance(data, addr, relevance=None):
    relevance_list = re.findall(r"\${(.*?)}", str(addr)) #address中需要替换的字段列表
    if len(relevance_list) == 0:
        return addr
    else:
        relevance_list = list(set(relevance_list))
        if len(relevance_list) == 1:
            mark_list = jsonpath.jsonpath(data,'$..{}'.format(relevance_list[0])) #请求数据中对应的需要替换的key的value值
            if mark_list == []:
                logging.error("依赖的关联值编写有问题:\n%s" % relevance_list[0])
            else:
                mark = mark_list[0]
                addr = str(addr).replace("${" + relevance_list[0] + "}", mark) #取第一个返回值进行替换
                return addr
        else:
            for rel in relevance_list:
                mark_list = jsonpath.jsonpath(data, '$..{}'.format(rel))
                if mark_list == []:
                    break
                mark = mark_list[0]
                addr = str(addr).replace("${" + rel + "}", mark)  # 取第一个返回值进行替换
                return addr


def get_address_relevance(data, addr, relevance=None):
    relevance_list = re.findall(r"\${(.*?)}", str(addr)) #address中需要替换的字段列表

    if len(relevance_list) == 0:
        return addr
    else:
        relevance_list = list(set(relevance_list))
        if len(relevance_list) == 1:
            if '[' in relevance_list[0]:
                m = str(relevance_list[0]).split('[')[0]
                n = str(relevance_list[0]).split('[')[1].replace(']','')
                mark_list = jsonpath.jsonpath(data, '$..{}'.format(m))
                if mark_list == False:
                    logging.error("依赖的关联值编写有问题,直接返回原链接字段:\n%s" % relevance_list[0])
                else:
                    mark = mark_list[int(n)]
                    addr = str(addr).replace("${" + relevance_list[0] + "}", mark)
                return addr
            else:
                mark_list = jsonpath.jsonpath(data,'$..{}'.format(relevance_list[0])) #请求数据中对应的需要替换的key的value值
                if mark_list == False:
                    logging.error("依赖的关联值编写有问题:\n%s" % relevance_list[0])
                else:
                    mark = mark_list[0]
                    addr = str(addr).replace("${" + relevance_list[0] + "}", mark) #取第一个返回值进行替换
                return addr
        else:
            for rel in relevance_list:
                if '[' in rel:
                    m = str(rel).split('[')[0]
                    n = str(rel).split('[')[1].replace(']', '')
                    mark_list = jsonpath.jsonpath(data, '$..{}'.format(m))
                    if mark_list == []:
                        logging.error("依赖的关联值编写有问题:\n%s" % relevance_list[0])
                    else:
                        mark = mark_list[int(n)]
                        addr = str(addr).replace("${" + rel + "}", mark)
                else:
                    mark_list = jsonpath.jsonpath(data, '$..{}'.format(rel))  # 请求数据中对应的需要替换的key的value值
                    if mark_list == []:
                        logging.error("依赖的关联值编写有问题:\n%s" % rel)
                    else:
                        mark = mark_list[0]
                        addr = str(addr).replace("${" + rel + "}", mark)  # 取第一个返回值进行替换
            return addr


# def get_addr_relevance(data, addr, relevance=None):
#     global __relevance
#     # 获取关联键列表
#     relevance_list = re.findall(r"\${(.*?)}", str(addr))
#
#     # 去除参数[n]标识
#     for index, value in enumerate(relevance_list):
#         mark = re.findall(r"\[\-?[0-9]*\]", value)
#         # if mark:
#         #     relevance_list[index] = value.strip(mark[0])
#         for m in mark:
#             value = value.replace(m, '')
#         relevance_list[index] = value
#
#     # 去除重复参数
#     relevance_list = list(set(relevance_list))
#     logging.debug("获取关联键列表:\n%s" % relevance_list)
#
#     # 判断关联键和源数据是否有值
#     if (not data) or (not relevance_list):
#         return relevance
#
#     # 判断是否存在其他关联键对象
#     if not relevance:
#         relevance = dict()
#
#     # 遍历关联键
#     for each in relevance_list:
#         relevance_value = get_value(data, each)
#         relevance = relevance_value[0]
#     addr = str(addr).replace("${" + each + "}", str(relevance))
#     logging.debug("提取关联键对象:\n%s" % relevance)
#     logging.debug("提取新的地址:\n%s" % addr)
#     return addr

# def getvalue(data, value,_list):
#     """迭代获取数据中的值，与上面的递归不一样，将每个前置条件中字段值将在一个集合
#     :param data:
#     :param value:
#     :return:
#     """
#     if value in str(data):
#         if isinstance(data, dict):
#             for key in data:
#                 if isinstance(data[key], dict):
#                     getvalue(data[key], value,_list)
#                 elif isinstance(data[key], list):
#                     for each in data[key]:
#                         if isinstance(each, dict):
#                             getvalue(each, value,_list)
#                     else:
#
#                         if str(value) in str(key):
#                             _list.append(data[key])
#                 else:
#                     if isinstance(data[key], str):
#                         print("data[key]:",data[key])
#                         if data[key][0] == '{' :
#                             data = literal_eval(data[key].replace('null','None'))
#                             getvalue(data, value, _list)
#                         elif str(value) in str(key):
#                             _list.append(data[key])
#         elif isinstance(data, list):
#             for key in data:
#                 if isinstance(key, dict):
#                     # __relevance = get_value(key, value)
#                     # break
#                     getvalue(key, value,_list)
#
#         return _list


def getvalue(data, value,_list):
    valueList = jsonpath.jsonpath(data, '$..{}'.format(value))
    _list = valueList
    return _list